from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
import redis
import random
import string
from myapp.models import *
from captcha.image import ImageCaptcha
from django.http import HttpResponse
from rest_framework.response import Response
from rest_framework import status
import json
import pypinyin
import re

class Yan(APIView):
    def get(self,request,uuid):
        red = redis.Redis(db=3)
        code = ''.join(random.sample(string.ascii_letters + string.digits,6))
        img = ImageCaptcha()
        imgcode = img.generate(code)

        red.setex('user_{}'.format(uuid),60*3,code)
        return HttpResponse(imgcode,content_type='image/png')


class Login(APIView):
    def post(self,request):
        number = request.data.get('number')
        password = request.data.get('password')
        code = request.data.get('code')
        uuid = request.data.get('uuid')
        red = redis.Redis(db=3)
        ret = red.get('user_{}'.format(uuid))
        if ret:
            if ret.decode() != code:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'message':'验证码错误'})
        else:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'message':'验证码过期'})

        user = User.objects.filter(number=number,password=password).first()
        if user:
            return Response({'code':status.HTTP_200_OK,'message':'登录成功'})
        else:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'message':'用户不存在'})


# 我的好友列表加入到缓存中
# 缓存：
# 先从缓存中查找数据，
# 如果有，就返回
# 没有，去数据库中查找数据
# 数据库有，写入缓存，返回数据，
# 数据库没有，返回空
def cates(user_id):
    red = redis.Redis(db=3)
    ret = red.get('user_{}_profile'.format(user_id))
    if ret is not None:
        user_dist = json.loads(ret)
        return user_dist
    else:
        filt = Friend.objects.filter(user_id=user_id,shield=1).all()
        
        if filt:
            my_list = []
            for i in filt:
                user = User.objects.filter(id=i.friend_id).first()
                my_list.append({
                    'name':user.name,
                    'number':user.number,
                    'password':user.password,
                })
            try:
                red.setex('user_{}_profile'.format(user_id),60*3,json.dumps(my_list))
                return json.loads(json.dumps(my_list))
            except Exception as e:
                print(e)
        else:
            return None


class Allfriend(APIView):
    def get(self,request):
        user_id = request.query_params.get('user_id')
        user = cates(user_id)
        if user:
            return Response({'code':status.HTTP_200_OK,'message':'获取成功'})
        else:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'message':'没有好友'})

class Pai(APIView):
    def get(self,request):
        user_id = request.query_params.get('user_id')
        ste = Friend.objects.filter(user_id=user_id,shield=1).all()

        my_list = []
        for i in ste:
            user = User.objects.filter(id=i.friend_id).first()
            my_list.append({
                'name': user.name,
                'number': user.number,
                'password': user.password,
            })

        # 首字母+字典 -- 新列表
        shou_dict = []
        # 首字母组成的新列表
        initials_list = []
        # 特殊名字的列表
        teshu_list = []
        for i in my_list:
            name = i.get('name')
            u = pypinyin.pinyin(name,style=pypinyin.FIRST_LETTER)
            u = u[0][0]
            rest = re.match('[A-Z]',u.upper()[0])
            if rest:
                shou_dict.append({
                    'name':i['name'],
                    'img':i['img'],
                    'show':u.upper()[0]
                })
                initials_list.append(u.upper()[0])
            else:
                teshu_list.append(i)
        sort_hou = sorted(initials_list)

        res = []
        for i in sort_hou:
            for j in shou_dict:
                if i== j['show']:
                    res.append(j)
        return Response({'code':status.HTTP_200_OK,'message':'获取OK'})

class Friend_circ(APIView):
    def get(self,request):
        user_id = request.query_params.get('user_id')
        fri = Friend_circle.objects.filter(user_id=user_id).all()

        res = []
        for i in fri:
            res.append({
                'id':i.id,
                'video':i.video,
                'text':i.text,
                'release_time':str(i.release_time),
                'img':[]
            })
        for i in res:
            img = Friend_img.objects.filter(fr_cir=i['id']).all()
            for j in img:
                i['img'].append(j.img)
        return Response({'code':status.HTTP_200_OK,'message':'获取成功'})


class Shield(APIView):
    def put(self,request):
        user_id = request.data.get('user_id')
        friend_id = request.data.get('friend_id')
        friend = Friend.objects.filter(user_id=user_id,friend_id=friend_id).first()
        if friend.shield == 1:
            friend.shield = 0
            friend.save()
            return Response({'code':status.HTTP_200_OK,'message':'已屏蔽'})
        elif friend.shield == 0:
            friend.shield = 1
            friend.save()
            return Response({'code':status.HTTP_200_OK,'message':'已取消屏蔽'})
